<template>
  <div class="vtext" ref="vtext">
    <span :style="{marginLeft:'-'+animateX+'px'}" :class="[getModeClass(mode)]" ref="textDom">
      {{text}}
    </span>
    <span v-if="marquee_start" :key="text" :class="['marquee2',getModeClass(mode)]" ref="textDom">
      {{text}}
    </span>
  </div>
</template>

<script setup>
import {nextTick, onMounted, onUnmounted, ref, toRefs, watch} from "vue";

let textDom = ref(null);
let vtext = ref(null);
let marquee_start = ref(false);
let propsDef = defineProps({
  text: String,
  width: {
    type: String,
    default: "100%"
  },
  height: {
    type: String,
    default: "auto"
  },
  mode: {
    type: String,
    default: "ellipsis"
  }
});
let props = toRefs(propsDef);
let vwidth = ref(0);
let twidth = ref(0);

let animateX = ref(0);

let timer = null;
watch(marquee_start,(newData)=>{
  if(newData){
    timer = setInterval(function (){
      animateX.value += 0.2;
      if(animateX.value > twidth.value + 50){
        animateX.value = 0;
      }
    },10);
  }else{
    clearInterval(timer);
    animateX.value = 0;
  }

})

onMounted(()=>{
  watch([props.text,props.mode], () => {
    nextTick(() => {
      setTimeout(() => {
        twidth.value = textDom.value?.clientWidth ?? 0;
        vwidth.value = vtext.value?.clientWidth ?? 0;
        if (twidth.value > vwidth.value && propsDef.mode === 'marquee') {
          marquee_start.value = true;
        } else{
          marquee_start.value = false;
        }
      });
    });
  }, {
    immediate: true
  });
})

onUnmounted(()=>{
  clearInterval(timer);
})


// ellipsis marquee
function getModeClass(mode) {
  return mode;
}
</script>

<style lang="scss" scoped>

@keyframes marquee {
  0% {
    transform: translateX(1.6rem);
  }
  100% {
    transform: translateX(-100%);
  }
}

.vtext {
  display: flex;
  overflow: hidden;
  .ellipsis {
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: keep-all;
    white-space: nowrap;
    font-size: inherit;
  }

  .marquee2{
    margin-left: 50px;
  }

  .marquee {
    flex-grow: 0;
    word-break: keep-all;
    white-space: nowrap;
    font-size: inherit;

    &.start {
      animation: marquee 5s infinite;
      animation-timing-function: linear;
    }
  }
}
</style>